import React, { Component, createRef } from 'react'
// 还可以通过ref完成父子组件间的传值
// ref绑定在【自定义类组件】时，可以得到组件实例对象，通过此实例对象完成传值
// 默认ref不能直接绑定在函数组件上

class Child extends Component {
  state = {
    name: 'child标题'
  }

  setName = (name) => {
    this.setState({ name })
  }

  render() {
    return (
      <div>
        <h3>child组件 -- {this.state.name}</h3>
      </div>
    )
  }
}

class App extends Component {
  childRef = createRef()

  state = {
    count: 100
  }

  setCount = (n) => {
    this.setState((state) => ({
      count: state.count + n
    }))
  }

  render() {
    return (
      <div>
        <h2>app组件</h2>
        <button
          onClick={() => {
            // console.log(this.childRef.current)
            this.childRef.current.setName(Date.now())
          }}
        >
          获取子组件中的name数据
        </button>
        <hr />
        {/* 默认情况下只能对类组件进行绑定ref属性 */}
        <Child ref={this.childRef} />
      </div>
    )
  }
}

export default App
